{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true,
    "ExecuteTime": {
     "end_time": "2025-03-14T06:46:40.231595Z",
     "start_time": "2025-03-14T06:38:39.684577Z"
    }
   },
   "source": [
    "import random\n",
    "import pandas as pd\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.linear_model import LogisticRegression\n",
    "from sklearn.tree import DecisionTreeClassifier\n",
    "from sklearn.ensemble import RandomForestClassifier\n",
    "from sklearn.metrics import precision_score, recall_score, f1_score, roc_auc_score, accuracy_score\n",
    "import numpy as np\n",
    "\n",
    "# 读取生成的数据\n",
    "user_behavior_data = pd.read_csv('tianchi_fresh_comp_train_user.csv')\n",
    "item_subset_data = pd.read_csv('tianchi_fresh_comp_train_item.csv')\n",
    "\n",
    "# 数据关联，通过 item_id 关联用户行为数据和商品子集数据\n",
    "#merged_data = pd.merge(user_behavior_data, item_subset_data, on='item_id', how='inner')\n",
    "merged_data = pd.merge(user_behavior_data, item_subset_data, on='item_id', how='left')\n",
    "\n",
    "# 检查合并后的数据是否为空\n",
    "if merged_data.empty:\n",
    "    print(\"合并后的数据为空，请检查数据关联条件。\")\n",
    "else:\n",
    "    # 特征工程\n",
    "    # 提取时间特征\n",
    "    merged_data['time'] = pd.to_datetime(merged_data['time'])\n",
    "    merged_data['hour'] = merged_data['time'].dt.hour\n",
    "    merged_data['day_of_week'] = merged_data['time'].dt.dayofweek\n",
    "\n",
    "    # 对行为类型进行 one - hot 编码\n",
    "    behavior_type_dummies = pd.get_dummies(merged_data['behavior_type'], prefix='behavior_type')\n",
    "    merged_data = pd.concat([merged_data, behavior_type_dummies], axis=1)\n",
    "\n",
    "    # 选择特征和目标变量\n",
    "    features = ['hour', 'day_of_week'] + [col for col in merged_data.columns if 'behavior_type_' in col]\n",
    "    target = merged_data['behavior_type'] == 4  # 购买行为作为目标\n",
    "\n",
    "    # 再次检查特征和目标变量是否为空\n",
    "    if len(features) == 0 or target.empty:\n",
    "        print(\"特征或目标变量为空，请检查特征选择条件。\")\n",
    "    else:\n",
    "        # 划分训练集和测试集\n",
    "        X_train, X_test, y_train, y_test = train_test_split(merged_data[features], target, test_size=0.2, random_state=42)\n",
    "\n",
    "        # 定义三种模型\n",
    "        models = {\n",
    "            'Logistic Regression': LogisticRegression(),\n",
    "            'Decision Tree': DecisionTreeClassifier(),\n",
    "            'Random Forest': RandomForestClassifier()\n",
    "        }\n",
    "\n",
    "        # 训练和评估模型\n",
    "        for model_name, model in models.items():\n",
    "            model.fit(X_train, y_train)\n",
    "            y_pred = model.predict(X_test)\n",
    "            y_pred_proba = model.predict_proba(X_test)[:, 1]\n",
    "\n",
    "            # 计算评估指标\n",
    "            precision = precision_score(y_test, y_pred)\n",
    "            recall = recall_score(y_test, y_pred)\n",
    "            f1 = f1_score(y_test, y_pred)\n",
    "            auc_roc = roc_auc_score(y_test, y_pred_proba)\n",
    "            accuracy = accuracy_score(y_test, y_pred)\n",
    "\n",
    "            print(f\"Model: {model_name}\")\n",
    "            print(f\"Precision: {precision}\")\n",
    "            print(f\"Recall: {recall}\")\n",
    "            print(f\"F1 - score: {f1}\")\n",
    "            print(f\"AUC - ROC: {auc_roc}\")\n",
    "            print(f\"Accuracy: {accuracy}\")\n",
    "            print(\"-\" * 50)\n",
    "\n",
    "        # 业务指标计算\n",
    "        # 1. 用户购买转化率\n",
    "        total_active_users = merged_data['user_id'].nunique()\n",
    "        purchased_users = merged_data[merged_data['behavior_type'] == 4]['user_id'].nunique()\n",
    "        conversion_rate = purchased_users / total_active_users\n",
    "        print(f\"用户购买转化率: {conversion_rate}\")\n",
    "\n",
    "        # 2. 整体GMV\n",
    "        \n",
    "        # 这里简单假设商品价格为1，实际需要根据具体数据修改\n",
    "        # 计算购买行为对应的商品数量\n",
    "        purchase_behavior = merged_data[merged_data['behavior_type'] == 4]\n",
    "        total_gmv = len(purchase_behavior)\n",
    "        print(f\"整体GMV: {total_gmv}\")\n",
    "\n",
    "        # 3. 点击率（CTR）\n",
    "        # 假设 exposure_count 是推荐商品曝光量，click_count 是推荐商品点击量\n",
    "        # 这里简单模拟，实际需要根据推荐日志计算\n",
    "        exposure_count = len(merged_data)\n",
    "        click_count = len(merged_data[merged_data['behavior_type'] == 1])\n",
    "        ctr = click_count / exposure_count\n",
    "        print(f\"点击率（CTR）: {ctr}\")\n",
    "\n",
    "        # 4. 用户活跃度\n",
    "        active_users = merged_data['user_id'].nunique()\n",
    "        print(f\"用户活跃度: {active_users}\")\n",
    "\n",
    "        # 衍生指标计算\n",
    "        # 1. 用户兴趣标签覆盖率\n",
    "        # 假设 labeled_users 是打标用户数，total_users 是总用户数\n",
    "        # 这里简单模拟\n",
    "        labeled_users = random.randint(100, 300)\n",
    "        total_users = merged_data['user_id'].nunique()\n",
    "        interest_label_coverage = labeled_users / total_users\n",
    "        print(f\"用户兴趣标签覆盖率: {interest_label_coverage}\")\n",
    "\n",
    "        # 2. 商品流行度\n",
    "        # 计算商品子集被浏览/收藏/加购的总次数\n",
    "        popularity_items = merged_data[merged_data['behavior_type'].isin([1, 2, 3])]['item_id'].count()\n",
    "        print(f\"商品流行度: {popularity_items}\")\n",
    "\n",
    "        # 3. 行为序列长度\n",
    "        # 计算每个用户单次会话中的行为次数\n",
    "        behavior_sequence_length = merged_data.groupby('user_id')['behavior_type'].count().mean()\n",
    "        print(f\"行为序列长度: {behavior_sequence_length}\")"
   ],
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Model: Logistic Regression\n",
      "Precision: 1.0\n",
      "Recall: 1.0\n",
      "F1 - score: 1.0\n",
      "AUC - ROC: 1.0\n",
      "Accuracy: 1.0\n",
      "--------------------------------------------------\n",
      "Model: Decision Tree\n",
      "Precision: 1.0\n",
      "Recall: 1.0\n",
      "F1 - score: 1.0\n",
      "AUC - ROC: 1.0\n",
      "Accuracy: 1.0\n",
      "--------------------------------------------------\n",
      "Model: Random Forest\n",
      "Precision: 1.0\n",
      "Recall: 1.0\n",
      "F1 - score: 1.0\n",
      "AUC - ROC: 1.0\n",
      "Accuracy: 1.0\n",
      "--------------------------------------------------\n",
      "用户购买转化率: 0.8827\n",
      "整体GMV: 248800\n",
      "点击率（CTR）: 0.9439781559616937\n",
      "用户活跃度: 20000\n",
      "用户兴趣标签覆盖率: 0.01115\n",
      "商品流行度: 25237330\n",
      "行为序列长度: 1274.3065\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "",
   "id": "bd284fa28ff8168e"
  },
  {
   "metadata": {},
   "cell_type": "code",
   "outputs": [],
   "execution_count": null,
   "source": "",
   "id": "8f37f44c712ab458"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
